package net.wangds.auth.account.service;

import net.wangds.spring.utils.SpringUtils;
import net.wangds.auth.account.comp.GeneralAccountComp;
import net.wangds.auth.account.entity.GeneralAccountEntity;
import net.wangds.auth.module.UserStatusEnum;
import net.wangds.data.RemovedEnum;
import net.wangds.log.helper.LogHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 通用的用户服务.
 * <p>
 *     各应用应参考本类实现自己的UserDetailsService.
 * </p>
 */
@Service
@Profile({"general-auth"})
public class GeneralUserDetailService implements UserDetailsService {

    @Autowired
    private GeneralAccountComp mmCmpAcc;

    @Override
    public UserDetails loadUserByUsername(String loginname) throws UsernameNotFoundException {
        UserDetails res;
        LogHelper.dev("加载用户信息："+loginname);
        // LogHelper.debug(()->"用户登录信息:"+ loginname, new Throwable());
        Optional<GeneralAccountEntity> opt = mmCmpAcc.findNormalUserByLoginName(loginname);
        if(opt.isPresent()){
          res =   opt.get();
        }else if(StringUtils.equalsIgnoreCase("username", loginname)) {
            GeneralAccountEntity r = new GeneralAccountEntity();
            r.setLoginname(loginname);
            r.setPassword(new BCryptPasswordEncoder().encode("1234"));
            r.setStatus(UserStatusEnum.NORMAL);
            r.setRemoved(RemovedEnum.NORMAL);
            res = r;
        }else {
            String msg = SpringUtils.getMessage("mod_common_auth_user_not_found", loginname);
            LogHelper.debug(msg);
            throw new UsernameNotFoundException(msg);
        }

        //LogHelper.debug(()->"用户登录结果:"+ JsonUtils.toJsonStr(res));

        return res;
    }
}
